const { Controller } = require('varal');
const { Station, sequelize } = require('../../models');
const { QueryTypes, Op } = require('sequelize');
const { listToTree } = require("../../helpers/function");

class StationController extends Controller {
	async index() {
		//const { 'region[0]': province_id, 'region[1]': city_id, 'region[2]': district_id, region, page = 1, page_size = 100 } = this.app.fields;
		const { region, page = 1, page_size = 100 } = this.app.fields;

		const serv = this.app.service('StationService');

		const where = {
			region
		}

		const sorter = [
			[sequelize.fn('JSON_EXTRACT', sequelize.col('Station.region'), sequelize.literal(`'$[${0}].value'`)), 'asc'],
			[sequelize.fn('JSON_EXTRACT', sequelize.col('Station.region'), sequelize.literal(`'$[${1}].value'`)), 'asc'],
			[sequelize.fn('JSON_EXTRACT', sequelize.col('Station.region'), sequelize.literal(`'$[${2}].value'`)), 'asc']
		];

		const { data } = await serv.get(where, page, page_size, sorter);

		//获取所有省市区信息
		const regionList = [];
		await Station.findAll({
			attributes: ['region']
		}).then((data) => data.map((d) => {
			const region = d.region || [];

			if (region[0]?.value) regionList.push({ id: region[0].value, name: region[0].label, parent_id: 0 });
			if (region[1]?.value) regionList.push({ id: region[1].value, name: region[1].label, parent_id: region[0].value });
			if (region[2]?.value) regionList.push({ id: region[2].value, name: region[2].label, parent_id: region[1].value });
		}));

		const regionOptions = listToTree(Object.values(Object.fromEntries(Object.entries(regionList).map((d) => {
			d[0] = d[1].id;
			return d;
		}))), 0);

		this.app.json({
			err_code: 0,
			data: {
				data,
				region_options: regionOptions
			}
		})
	}
}

exports = module.exports = StationController;
